 
/* Keeps track of the DOM element currently displayed */
var currentElement;

/* Holds the DIV from the original HTML in case we 
   want to swap it back in */
var view_area;

/* The MochiKit asynchronous request object */
var thisRequest;

/* A couple shorthand CSS elements */
var headerClass = {'class': 'commentheader'};
var dataClass = {'class': 'commentdata'};

/*
 * Called when the user clicks on the "View Comments"
 * link. id = the primary key of the blog 
 */
function viewComments(id) {
  currentElement = DIV(null, "Fetching...")
  view_area = getElement("comment_view_area");
  swapDOM(view_area, currentElement);
  thisRequest = loadJSONDoc("/simpleblog/getComments/"+id);
  thisRequest.addCallbacks(commentsReady, commentsError);
}

/*
 * Called when the user clicks on the "Hide Comments"
 * link. It swaps the original DIV in place of the comment list.
 */
function hideComments() {
  swapDOM(currentElement, view_area);
  currentElement = view_area;
}

/*
 * This function formats a single row of the comment display table
 */
row_display = function (row) {
    var d = rating_choices;
    return TR(dataClass, 
              TD(dataClass, row.fields.content),
              TD(dataClass, rating_choices[row.fields.rating]));
}

/*
 * Called when the comment model objects are received from the 
 * server.
 */
var commentsReady = function (meta) {
  var commentList = evalJSONRequest(thisRequest.results[0]);

  var newTable = TABLE({'class': 'commenttable'},
      THEAD(headerClass, TD(headerClass, "Comment"), 
                         TD(headerClass, "Rating")),
      TBODY(null, map(row_display, commentList))
    );

  var hide = P(null, 'Hide ', 
               A({'href': 'javascript:hideComments()'}, 'comments'));
  if (is_authenticated) {
    var a = P(null, 'Enter new ', 
              A({'href': 'comment/add/'}, 'comment'));
    var newDiv = DIV({'class': 'footer'}, hide, newTable, a);
  } else {
    var newDiv = DIV({'class': 'footer'}, hide, newTable);
  }
  swapDOM(currentElement, newDiv);
  currentElement = newDiv;
}

/*
 * Error function called if an error occurs while 
 * fetching the async data
 */
var commentsError = function (err) {
  alert("commentsError");
}